<template>
  <div id="panel">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          :label-position="'right'"
        >
          <el-form-item label="" prop="type">
            <el-radio-group
              v-model="queryParams.timeType"
              size="medium"
              @change="chosetime"
            >
              <el-radio-button
                v-for="option in timetypesel"
                :key="option.value"
                :label="option.value"
              >
                {{ option.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="riverid">
            <el-form-item class="speItem">
              <el-date-picker
                popper-class="popperClass"
                v-model="startTime"
                :type="selectedType"
                :format="formatByType(queryParams.dataEnum)"
                placeholder="开始时间"
                :value-format="formatByType(queryParams.dataEnum)"
                :picker-options="pickerOptions"
                :disabled="ifdisabled"
                @change="checkDuration"
                :clearable="false"
                :key="timer + 2"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item class="speItem">
              <el-date-picker
                popper-class="popperClass"
                v-model="endTime"
                :type="selectedType"
                :format="formatByType(queryParams.dataEnum)"
                style="margin-left: 10px"
                placeholder="结束时间"
                :value-format="formatByType(queryParams.dataEnum)"
                :picker-options="pickerOptions"
                :disabled="ifdisabled"
                @change="checkDuration"
                :key="timer + 1"
                :clearable="false"
              >
              </el-date-picker>
            </el-form-item>
          </el-form-item>
          <el-form-item label="">
            <el-radio-group v-model="queryParams.type" size="medium">
              <el-radio-button label="single">单因子</el-radio-button>
              <el-radio-button label="multi">多因子</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="queryParams.type === 'single'">
            <el-radio-group v-model="selectedOption">
              <el-radio-button
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-else>
            <el-checkbox-group v-model="selectedMultiFactors">
              <el-checkbox-button
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                >{{ item.label }}</el-checkbox-button
              >
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
              style="padding: 10px"
              >查询</el-button
            >
            <!-- <el-button @click="resetQuery" style="padding: 10px">
              <i class="iconfont icon-saoba"></i>
              清除
            </el-button> -->
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="never">
          <div slot="header">
            <span>污染物超标次数统计</span>
          </div>
          <div
            id="charTwo"
            ref="charTwo"
            style="height: 450px; width: 100%"
          ></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import getTime from "@/utils/getTime.js";
import { getMonitorFactor } from "@/api/dataResources/common";
import { updateDate, updateTime, updateTimeB } from "@/utils/ruoyi";
import {
  getWaterTrend,
  getWaterTrendDay,
  getWaterTrendMonth,
} from "@/api/waterBusiness/interface.js";
export default {
  name: "waterQuality",
  props: {
    dmid: {
      type: String,
      default: "",
    },
  },
  dicts: ["show"],
  data() {
    return {
      timer: new Date().getTime(),
      selectedOption: "高锰酸盐指数",
      options: [
        { label: "高锰酸盐指数" },
        { label: "氨氮" },
        { label: "总磷" },
        { label: "pH" },
        { label: "溶解氧" },
        { label: "化学需氧量" },
        { label: "总氮" },
        { label: "水温" },
        { label: "电导率" },
        { label: "浑浊度" },
        { label: "叶绿素a" },
        { label: "藻密度" },
        { label: "氟化物" },
      ],
      timetypesel: [
        {
          value: "hour",
          label: "小时",
        },
        {
          value: "day",
          label: "日",
        },
        {
          value: "month",
          label: "月",
        },
      ],
      selectedType: "datetime", // 默认选择日
      queryParams: {
        timeType: "hour",
        type: "single",
      },
      // 选择的类型
      selectType: "daterange",
      times: "",
      selectedMultiFactors: [],
      startTime: "",
      endTime: "",
      // echarts数据
      charData: {},
    };
  },
  watch: {
    "queryParams.timeType": {
      handler(newVal, oldVal) {
        console.log("让我看看时间类型", newVal);
        this.startTime = "";
        this.endTime = "";
        this.ifdisabled = false;
        if (newVal == "year") {
          this.selectedType = "year";
          this.pickerOptions = {};
        } else if (newVal == "month") {
          this.selectedType = "month";
          this.pickerOptions = {};
        } else if (newVal == "day") {
          this.selectedType = "date";
          this.pickerOptions = {};
        } else if (newVal == "hour") {
          this.selectedType = "datetime";
          this.pickerOptions = {};
        } else if (newVal == "minute") {
          this.selectedType = "datetime";
        } else {
          this.selectedType = "datetime";
          // this.startTime = this.endTime = updateTime();
          // this.ifdisabled = true;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.startTime = updateDate() + " 00:00:00";
    this.endTime = updateTime();
    // 默认获取小时数据
    this.getData();
  },
  mounted() {
    this.initChart();
  },
  methods: {
    // 时间类型选择变化
    chosetime(val) {
      console.log(val);
      this.timer = new Date().getTime();
      // this.queryParams.dataEnum = val;
      this.formatByType(val);
      if (val == "minute") {
        this.startTime = updateDate() + " 00:00";
        this.endTime = updateTimeB();
      } else if (val == "real") {
        this.startTime = updateDate() + " 00:00:00";
        this.endTime = updateTime();
      } else if (val == "hour") {
        // this.startTime = updateDate() + " 00";
        // this.endTime = getTime.getNowHour();
        this.startTime = updateDate() + " 00:00:00";
        this.endTime = updateTime();
      } else if (val == "day") {
        this.startTime = getTime.getNowMouth() + "-01";
        this.endTime = getTime.getNowDate();
      } else if (val == "month") {
        this.startTime = getTime.getNowYear() + "-01";
        this.endTime = getTime.getNowMouth();
      } else {
        this.startTime = "";
        this.endTime = "";
      }
      this.getData();
    },
    // 时间框改变事件
    checkDuration() {
      if (
        this.queryParams.dataEnum == "minute" ||
        this.queryParams.dataEnum == "real"
      ) {
        if (this.startTime && this.endTime) {
          let start = new Date(this.startTime + ":00:00");
          let end = new Date(this.endTime + ":00:00");
          let diff = end.getTime() - start.getTime();
          let maxDuration = 7 * 24 * 60 * 60 * 1000; // 7天的毫秒数

          if (diff > maxDuration) {
            this.$message.error("时间范围不得超过7天");
            // 重置结束时间或者开始时间以满足条件
            this.endTime = "";
          }
          if (start > end) {
            this.startTime = "";
            this.$modal.msgWarning("开始时间不能大于结束时间");
          }
        }
      } else if (this.queryParams.dataEnum == "hour") {
        let start = new Date(this.startTime + ":00:00");
        let end = new Date(this.endTime + ":00:00");
        if (start > end) {
          this.startTime = "";
          this.$modal.msgWarning("开始时间不能大于结束时间");
        }
      } else if (this.queryParams.dataEnum == "day") {
        let start = new Date(this.startTime + " 00:00:00");
        let end = new Date(this.endTime + " 00:00:00");

        if (start > end) {
          this.startTime = "";
          this.$modal.msgWarning("开始时间不能大于结束时间");
        }
      } else if (this.queryParams.dataEnum == "month") {
        let start = new Date(this.startTime);
        let end = new Date(this.endTime);

        if (start > end) {
          this.startTime = "";
          this.$modal.msgWarning("开始时间不能大于结束时间");
        }
      } else {
        debugger;
        let start = new Date(this.startTime);
        let end = new Date(this.endTime);

        if (start > end) {
          this.startTime = "";
          this.$modal.msgWarning("开始时间不能大于结束时间");
        }
      }
    },
    // 获取监测因子
    getMonitorFactor() {
      let query = {
        bussinessCategoryCode: "Auto",
      };
      getMonitorFactor(query).then((res) => {
        this.options = res.data.map((item) => ({
          // value: item.itemCode,
          value: item.eNName,
          label: item.itemName,
        }));
      });
    },
    //搜索
    handleQuery() {
      this.getData();
    },
    //重置、清除表单
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
    },
    // 根据选择类型格式化时间控件
    formatByType(type) {
      switch (type) {
        case "year":
          return "yyyy";
        case "month":
          return "yyyy-MM";
        case "day":
          return "yyyy-MM-dd";
        case "hour":
          return "yyyy-MM-dd HH";
        case "minute":
          return "yyyy-MM-dd HH:mm";
        case "real":
          return "yyyy-MM-dd HH:mm:ss";
      }
    },
    // 时间框改变事件
    checkDuration() {
      if (
        this.queryParams.dataEnum == "minute" ||
        this.queryParams.dataEnum == "real"
      ) {
        if (this.startTime && this.endTime) {
          debugger;
          let start = new Date(this.startTime + ":00:00");
          let end = new Date(this.endTime + ":00:00");
          let diff = end.getTime() - start.getTime();
          let maxDuration = 7 * 24 * 60 * 60 * 1000; // 7天的毫秒数

          if (diff > maxDuration) {
            this.$message.error("时间范围不得超过7天");
            // 重置结束时间或者开始时间以满足条件
            this.endTime = "";
          }
          if (start > end) {
            this.startTime = "";
            this.$modal.msgWarning("开始时间不能大于结束时间");
          }
        }
      } else if (this.queryParams.dataEnum == "hour") {
        let start = new Date(this.startTime + ":00:00");
        let end = new Date(this.endTime + ":00:00");
        if (start > end) {
          this.startTime = "";
          this.$modal.msgWarning("开始时间不能大于结束时间");
        }
      } else if (this.queryParams.dataEnum == "day") {
        let start = new Date(this.startTime + " 00:00:00");
        let end = new Date(this.endTime + " 00:00:00");

        if (start > end) {
          this.startTime = "";
          this.$modal.msgWarning("开始时间不能大于结束时间");
        }
      } else if (this.queryParams.dataEnum == "month") {
        let start = new Date(this.startTime);
        let end = new Date(this.endTime);

        if (start > end) {
          this.startTime = "";
          this.$modal.msgWarning("开始时间不能大于结束时间");
        }
      } else {
        debugger;
        let start = new Date(this.startTime);
        let end = new Date(this.endTime);

        if (start > end) {
          this.startTime = "";
          this.$modal.msgWarning("开始时间不能大于结束时间");
        }
      }
    },

    // 获取数据项
    getData() {
      let morearr = "";
      if (this.selectedMultiFactors.length > 0) {
        morearr = this.selectedMultiFactors.join(",");
      }
      let query = {
        id: this.dmid,
        startTime: this.startTime,
        endTime: this.endTime,
        items:
          this.queryParams.type == "single" ? this.selectedOption : morearr,
      };
      if (this.queryParams.timeType == "hour") {
        getWaterTrend(query).then((res) => {
          if (res.code == 200) {
            this.charData = res.data;
            this.initChart();
          }
        });
      } else if (this.queryParams.timeType == "day") {
        getWaterTrendDay(query).then((res) => {
          if (res.code == 200) {
            this.charData = res.data;
            this.initChart();
          }
        });
      } else {
        getWaterTrendMonth(query).then((res) => {
          if (res.code == 200) {
            this.charData = res.data;
            this.initChart();
          }
        });
      }
    },
    // echarts
    initChart() {
      const series = [];
      const dataKeys = Object.keys(this.charData);

      dataKeys.forEach((key) => {
        if (key !== "dateList") {
          // 跳过x轴数据
          series.push({
            name: key, // 系列名称（如“电导率”）
            type: "line", // 柱状图类型
            data: this.charData[key].map((item) => Number(item)), // 转换为数字类型
            barWidth: 15, // 柱子宽度
            itemStyle: {
              borderRadius: 4, // 柱子圆角
            },
          });
        }
      });
      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        legend: {
          data: series.map((item) => item.name), // 图例数据（所有监测指标）
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: this.charData.dateList, // x轴为日期
            axisLabel: {
              rotate: 30, // 日期文字旋转30度，避免重叠
              // interval: 0, // 强制显示所有标签
            },
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
        series: series, // 系列数据
      };
      // let maChar = echarts.init(document.getElementById("waterQuality"));
      let maChar = echarts.init(this.$refs.charTwo);
      maChar.setOption(option);
      window.addEventListener("resize", function () {
        maChar.resize();
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
